package controllers;

import helpers.UrlHelper;

import java.io.IOException;
import java.util.TreeMap;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import models.DomainModel;

import data.DomainData;

public class HomeServlet extends HttpServlet {
	public void doGet(HttpServletRequest request, HttpServletResponse response)
		throws IOException, ServletException {
		TreeMap check = new TreeMap();
		
		request.setAttribute("check", check);
		request.setAttribute("name", "");
		try {
			request.getRequestDispatcher("/pages/home_page.jsp").forward(request, response);
		} catch (ServletException e) {
			//e.printStackTrace();
		}
		
	}
	
	public void doPost(HttpServletRequest request, HttpServletResponse response)
		throws IOException, ServletException {
		TreeMap check = new TreeMap();
		String name = (String) request.getParameter("name");
		
		if (name == null || !UrlHelper.checkDomain(name)) {
			check.put("name", "domain is not valid!");
		}
		
		if (check.size() == 0) {
			DomainData domainData = new DomainData();
			DomainModel domain = domainData.get(name);
			if (domain == null) {
				response.sendRedirect("/process/" + name);
				return;
			} else {
				response.sendRedirect("/info/" + name);
				return;
			}
		}
		
		request.setAttribute("check", check);
		request.setAttribute("name", name);
		try {
			request.getRequestDispatcher("/pages/home_page.jsp").forward(request, response);
		} catch (ServletException e) {
			//e.printStackTrace();
		}
	}
}
